package com.yowasa.xiuxian.service.helper;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yowasa.xiuxian.entity.po.XiuxianUserBaseInfoPO;
import com.yowasa.xiuxian.entity.po.XiuxianUserEmail;
import com.yowasa.xiuxian.mapper.XiuxianUserBaseInfoMapper;
import com.yowasa.xiuxian.mapper.XiuxianUserEmailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class EmailHelper {

    @Autowired
    private XiuxianUserEmailMapper xiuxianUserEmailMapper;

    @Autowired
    private XiuxianUserBaseInfoMapper xiuxianUserBaseInfoMapper;

    public List<XiuxianUserEmail> selectEmaliByUserId(Long id) {
        return xiuxianUserEmailMapper.selectList(
                new LambdaQueryWrapper<XiuxianUserEmail>()
                        .eq(XiuxianUserEmail::getAccountId,id)
                        .and(w-> w.eq(XiuxianUserEmail::getItemStatus,0).or().eq(XiuxianUserEmail::getReadStatus,0)));
    }

    public List<XiuxianUserEmail> selectAllEmaliByUserId(Long id) {
        return xiuxianUserEmailMapper.selectList(new LambdaQueryWrapper<XiuxianUserEmail>().eq(XiuxianUserEmail::getAccountId,id));
    }

    public XiuxianUserEmail selectById(int i) {
        return xiuxianUserEmailMapper.selectById(i);
    }

    public void insert(XiuxianUserEmail email) {
        xiuxianUserEmailMapper.insert(email);
    }

    public void update(XiuxianUserEmail email) {
        xiuxianUserEmailMapper.updateById(email);
    }

    public void sendEmali(String name, String type, String num,String msg) {
        List<XiuxianUserBaseInfoPO> xiuxianUserBaseInfoPOS = xiuxianUserBaseInfoMapper.selectList(new LambdaQueryWrapper<XiuxianUserBaseInfoPO>().eq(XiuxianUserBaseInfoPO::getDead,0));
        for (XiuxianUserBaseInfoPO user : xiuxianUserBaseInfoPOS){
            XiuxianUserEmail email = new XiuxianUserEmail();

            email.setItemStatus(0);
            email.setReadStatus(0);
            email.setTitle("全服补偿");
            email.setMsg(msg);
            email.setAccountId(user.getId());
            email.setCreateTime(new Date());
            email.setFromAccount(0L);
//            {"type":1,"name":"金疮药","num":10,"quality":2}
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type",type);
            jsonObject.put("name",name);
            jsonObject.put("num",num);
            jsonObject.put("quality",2);
            email.setExtra(jsonObject.toString());
            xiuxianUserEmailMapper.insert(email);
        }
    }

    public void updateStatusByUser(Long id) {
        xiuxianUserEmailMapper.updateStatusByUserId(id);
    }

    public XiuxianUserEmail selectByIdForUpdate(int i) {
        return xiuxianUserEmailMapper.selectOne(new LambdaQueryWrapper<XiuxianUserEmail>().eq(XiuxianUserEmail::getId,i).last("for update"));
    }
}
